//
//  ViewController.swift
//  YWT-Swift
//
//  Created by czh on 2016/9/28.
//  Copyright © 2016年 zwl. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

// MARK:- 定义全局常量
private let reuseID = "reuseID"

// MARK:- 类的声明
class ViewController: UIViewController {
    
    // MARK:- 懒加载属性
    fileprivate lazy var newsModel = [ZWLNewsModel]()
    fileprivate lazy var tableView : UITableView = {[unowned self] in
        
        let tableView = UITableView()
        tableView.frame = self.view.bounds
        tableView.dataSource = self
        tableView.register(UINib(nibName: "ZWLMyTableViewCell", bundle: nil), forCellReuseIdentifier: reuseID)
        return tableView
    }()
    
    // MARK:- 系统回调方法
    override func viewDidLoad() {
        super.viewDidLoad()
       
        setupNavBar()
        
        view.addSubview(tableView)
        
        loadData()
    
    }
    

}

// MARK:- 设置 UI 界面
extension ViewController {
    fileprivate func setupNavBar() {
        
        navigationController?.navigationBar.setBackgroundImage(UIImage(named: "reader_navigation_background"), for: .default)
        navigationItem.titleView = UIImageView(image: UIImage(named: "navigation_logo"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "navigation_search"), style: .plain, target: self, action: #selector(searchBtnClick))
        
    }
}

// MARK:- 事件监听函数
extension ViewController {
    @objc fileprivate func searchBtnClick() {
     
        let vc = UIStoryboard(name: "ZWLStaticTabVc", bundle: nil).instantiateInitialViewController()
        self.navigationController?.pushViewController(vc!, animated: true)
        
    }
}

// MARK:- tableView 的数据源方法
extension ViewController : UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.newsModel.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseID, for: indexPath) as! ZWLMyTableViewCell
        cell.model = self.newsModel[indexPath.row]
        
        cell.accessoryType = .disclosureIndicator
        
        return cell
    }
    
}

// MARK:- 网络请求
extension ViewController {

    fileprivate func loadData() {
        
        ZWLNetworkTool.sharedTools.requestData(type: .GET, URLString: "http://c.m.163.com/nc/article/list/T1348649079062/0-20.html", parameters: nil, successCallBack: { (resultData) -> (Void) in
            
            // 把二进制数据转换成 json 字符串
            guard let jsonStr = String(data: (resultData as? Data)!, encoding: .utf8) else { return }
            
            // 把 json 字符串转换成字典
            let resultDict = self.jsonToDict(text: jsonStr)
            
            // 取出里面的数据
            guard let dictArray = resultDict?["T1348649079062"] as? [[String : Any]] else { return }
            
            // 便利字典，把字典转换成模型
            for dict in dictArray {
                self.newsModel.append(ZWLNewsModel(dict: dict))
            }
            
            self.tableView.reloadData()
            
            
            }) { (error) -> (Void) in
                print(error)
        }
        
    }
    
    // MARK:- 把一个格式化好的 json 字符串转换成字典
    func jsonToDict(text: String) -> [String:AnyObject]? {
        if let data = text.data(using: String.Encoding.utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }

}
